<?php
$loader->requireOnce("includes/WorkingCalendar.class.php");     
/**
 * Controller Calendar actions
 */
class C_CalendarManager extends Controller {

	
    function C_CalendarManager ($template_mod = "general") {
        parent::Controller();
        $this->_db = $GLOBALS['frame']['adodb']['db'];   
    	if (Celini::getCurrentController() == 'CalendarManager') {
			$menu =& Menu::getInstance();
			$menu->currentSection = 'patient';
		}
        $this->template_mod = $template_mod;        
        $this->view->path = 'calendar_manager';
    } 

 	public function actionViewCalendar() {
 		return $this->view->render("view.html");
 	}
 	
 	public function actionCreateEventAjax(){
 		$eventId = $_GET['eventId'];
 		if(isset($eventId) && ($eventId != '' && $eventId !== 'undefined') ){
 			$event_array = Celini::newORDO('CalendarEvent')->getEvent($eventId);
 			$event = $event_array[0];
 			$user_list = Celini::newORDO('CalendarEventMap')->getUsers($eventId);
 			$this->assign('event', $event);
 			$this->assign('user_list', $user_list);
 		}
 		$employee_type_list = Celini::newORDO('EmployeeType')->getAll();
 		$this->assign('employee_type_list',$employee_type_list);
 		return $this->view->render("create_event.html");
 	}
 	
 	public function actionSaveEventAjax(){
 		
 		$me =& Me::getInstance();
 		$name = Sanitize::removeSpaces($_GET['name']);
 		$creator_id = $me->get_user_id();
 		$date_array = explode('/',$_GET['startDate']);
 		$start_date = $date_array[2].'-'.$date_array[1].'-'.$date_array[0];
 		$date_array = explode('/',$_GET['endDate']);
 		$end_date = $date_array[2].'-'.$date_array[1].'-'.$date_array[0];
 		$start_time = $_GET['startHour'].":".$_GET['startMinute'].":00";
		$end_time = $_GET['endHour'].":".$_GET['endMinute'].":00";
		$userIds = explode(',', $_GET['userArray']);
		$recur_type = $_GET['select_recursive_type'];
		$recur_data = '';
		if($recur_type == 2){
			$recur_data = '0000000';
			$dayWeek = $_GET['dayWeek'];
			foreach($dayWeek as $day){
				switch ($day){
					case 2:	
						$recur_data = substr_replace($recur_data,'1',0,1);
						break;
					case 3:
						$recur_data = substr_replace($recur_data,'1',1,1);
						break;
					case 4:
						$recur_data = substr_replace($recur_data,'1',2,1);
						break;
					case 5:
						$recur_data = substr_replace($recur_data,'1',3,1);
						break;
					case 6:
						$recur_data = substr_replace($recur_data,'1',4,1);
						break;
					case 7:
						$recur_data = substr_replace($recur_data,'1',5,1);
						break;
					case 8:
						$recur_data = substr_replace($recur_data,'1',6,1);
						break;
				}
			}
		}else if($recur_type == 3){
			$recur_data = '0000000';
		}else if($recur_type == 1){
			$recur_data = '1111111';
		}
		//echo $recur_data;
		//print_r($dayWeek);
		//return;
 		$calendar_event = Celini::newORDO('CalendarEvent');
 		$calendar_event_id = $calendar_event->AddEvent($_GET['eventId'],$name, $_GET['description'],
 													   $start_date, $end_date, $start_time, $end_time,
 													   $creator_id, $recur_type, $recur_data );											
		$result = Celini::newORDO('CalendarEventMap')->addUser($calendar_event_id, $userIds); 									
 		return ;
 	}
 	public function actionMapEventUserAjax(){
 		$calendar_event = Celini::newORDO('CalendarEvent')->getEvent($_GET['eventId']);
 		$this->assign('name', $calendar_event[0]['name']);
 		$this->assign('description', $calendar_event[0]['description']);
 		$this->assign('start_date', $calendar_event[0]['start_date']);
 		$this->assign('end_date', $calendar_event[0]['end_date']);
 		$this->assign('start_time', $calendar_event[0]['start_time']);
 		$this->assign('end_time', $calendar_event[0]['end_time']);
 		$this->assign('event_id', $calendar_event[0]['calendar_event_id']);
 		$user_list = Celini::newORDO('CalendarEventMap')->getUsers($_GET['eventId']);
 		$this->assign('user_list', $user_list);
 		return $this->view->render("map_event_user.html");
 	}
 	
 	public function actionSearchUserAjax(){
 		$search_string = $_GET['searchStr'];
 		$employeeTypeId = $_GET['employeeTypeId'];
 		$sql = "SELECT p.person_id, p.name, et.name employee_type
 				FROM employee e
 				LEFT JOIN person p ON (p.person_id = e.person_id)
 				LEFT JOIN employee_type et ON (e.employee_type_id = et.employee_type_id) 
 				WHERE ";
 		if($employeeTypeId !== 'all'){
 			$sql .= "e.employee_type_id = $employeeTypeId AND ";
 		}
 		
 		if (preg_match('/^[0-9]+$/', $search_string)) {
			$sql .= "pt.patient_code LIKE '%" . (int)$search_string . "%'";
		} else {
			$cleanedValue = mysql_real_escape_string($search_string);
			$cleanedValue = str_replace(array(',', '  '), ' ', $cleanedValue);
			$sql .= "p.name LIKE '%".$cleanedValue."%'";
		}
		$sql .= ' ORDER BY p.name ';
		$user_list = $this->_db->GetAll($sql); 
		return $this->buildSearchResult($user_list);				
 		
 	}
 	private function buildSearchResult($user_list){
 		$response = '';
 		if(isset($user_list) && $user_list!= ''){
 			$i = 1;
	 		foreach($user_list as $user){
				$response .= "<tr id='{$i}_row'>
								<td class='first'><span id='{$user['person_id']}_name_span'>{$user['name']}</span></td>
								<td><span id='{$user['person_id']}_employee_type_span'>{$user['employee_type']}</span></td>
								<td class='last' align='center'><a href='javascript:addUser({$user['person_id']},$i);'>".L10nHelper::_("Select")."</a></td>
								</tr>";
				$i++;
				 
			}
 		}
		return $response;		
 	}
 	
 	public function actionAddUserToEventAjax(){
 		$result = Celini::newORDO('CalendarEventMap')->addUser($_GET['eventId'], $_GET['userId']);
 		if($result === 1){
 			return '';
 		}
 		$name = Celini::newORDO('User')->getPersonName($_GET['userId']);
 		$response = "<tr>
						<td class='first'>$name</td>
						<td class='last'><a href='javascript:removeUser(".$_GET['userId'].");'>".L10nHelper::_("Unselect")."</a></td>
					</tr>";
 		return $response;
 	}
 	
	public function actionRemoveUserToEventAjax(){
 		Celini::newORDO('CalendarEventMap')->RemoveUser($_GET['eventId'], $_GET['userId']);
 		$user_list = Celini::newORDO('CalendarEventMap')->getUsers($_GET['eventId']);
 		$response = '';
 		if(isset($user_list) && $user_list != ''){
 			foreach($user_list as $user){
 				$response .= "<tr>
								<td class='first'>{$user['name']}</td>
								<td class='last'><a href='javascript:removeUser({$user['user_id']});'>".L10nHelper::_("Unselect")."</a></td>
								</tr>";
 			}
 		}
 		return $response;
 	}
 	
 	public function actionDeleteEventAjax(){
 		Celini::newORDO('CalendarEvent')->deleteEvent($_GET['eventId']);
 		$calendar_event_list = Celini::newORDO('CalendarEvent')->getAllEvents();
 		$response = '';
 		if(isset($calendar_event_list) && $calendar_event_list != ''){
 			foreach($calendar_event_list as $event){
 				$response .= 
 					"<tr>
						<td class='first'>
							<a href='javascript:map_event_users({$event['calendar_event_id']})'>{$event['name']}</a></td>
						<td>{$event['description']}&nbsp;</td>
						<td>{$event['start_date']}</td>
						<td>{$event['end_date']}</td>
						<td>{$event['start_time']} - {$event['end_time']}</td>
						<td align='center' class='last'>
							<a href='javascript:deleteEvent({$event['calendar_event_id']});'>Xóa</a></td>
					</tr>";
 			}
 		}
 		return $response; 
 	}
 	
 	public function actionGetEventListAjax(){
 		$calendar_event_list = Celini::newORDO('CalendarEvent')->getAllEvents();
 		$this->assign('event_list', $calendar_event_list);
 		return $this->view->render("view_event_list.html");
 	}
 	
 	public function actionMappingRelationshipAjax(){
 		$employee_type_list = Celini::newORDO('EmployeeType')->getAll();
 		$this->assign('employee_type_list',$employee_type_list);
 		return $this->view->render('mapping_relationship.html');
 	}
 	
 	public function actionGetUserByEmployeeTypeAjax(){
 		if(!isset($_GET['employee_type_id']) || $_GET['employee_type_id'] =='' ) return;
 		$employee_list = Celini::newORDO('Employee')->getUserList(array($_GET['employee_type_id']));
 		$response = '';
 		if(isset($employee_list) && $employee_list != ''){
 			foreach($employee_list as $employee){ 			
 				$response .= "<option value='{$employee['person_id']}' >{$employee['name']}</option>";
 			}
 		}
 		return $response;
 	}
 	
 	public function actionGetRelationalUserAjax(){
 		
 		$user_list = Celini::newORDO('CalendarRelationship')->getRelationalUser($_GET['employeeId']);
 		$response = '';
 		if(isset($user_list) && $user_list != ''){
 			foreach($user_list as $user){
 				$response .= "<tr id='{$user['relational_person_id']}_row'>
 								<td class='first'>{$user['name']}</td>
								<td>{$user['employee_type']}</td>
								<td class='last'><a href='javascript:removeUser({$user['relational_person_id']});'>".L10nHelper::_("Unselect")."</a></td>
							</tr>"; 
 			}
 		}
 		return $response;
 	}
 	
 	public function actionAddUserToRelationshipAjax(){
 		Celini::newORDO('CalendarRelationship')->addUser($_GET['personId'], $_GET['relational_personId']);
 		return;
 	}
 	
	public function actionRemoveUserFromRelationshipAjax(){
 		Celini::newORDO('CalendarRelationship')->removeUser($_GET['personId'], $_GET['relational_personId']);
 		return;
 	}
}
?>